<script lang="ts" setup>
import { artAddChannelsService, artEditChannelsService } from '@/api/article'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
const dialogVisible = ref(false)
const formModel = ref({
  id: '',
  cate_name: '',
  cate_alias: ''
})

const rules = ref({
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名称必须是1-10的非空格字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15个大小写字母和数字组成的字符串',
      trigger: 'blur'
    }
  ]
})

const formRef = ref()
const handleSubmit = async () => {
  // 校验
  await formRef.value.validate()
  // 判断
  if (formModel.value.id) {
    // 编辑分类
    await artEditChannelsService(formModel.value)
  } else {
    // 添加分类
    await artAddChannelsService(formModel.value)
  }
  // 成功提示框
  ElMessage({
    type: 'success',
    message: formModel.value.id ? '编辑成功' : '添加成功'
  })
  // 通知父组件
  emit('success')
  // 关闭弹窗
  dialogVisible.value = false
}

// 子传父回显
const emit = defineEmits(['success'])

// 暴露一个方法接收参数，并打开对话框
// 如果传入的参数是一个 obj, 则为编辑弹窗；如果传入的是空对象{}，则为添加弹窗
const openDialog = (obj) => {
  dialogVisible.value = true
  formModel.value = { ...obj } // 此处不能直接赋值，赋值的是引用地址，会随时改变；应该用浅拷贝
}

defineExpose({
  openDialog
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑分类' : '添加分类'"
    width="500"
  >
    <el-form
      :model="formModel"
      label-width="120px"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input v-model="formModel.cate_name" />
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input v-model="formModel.cate_alias" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit()"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
